#!/usr/bin/env python

"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Yapyturing
Juampe Lopez, october 2008
"""

import sys
import re
from TM_rule import *

tm_filename = sys.argv[1]
tm_rules_file = open (tm_filename, "r")

TM_rules = []
TM_input = ['>','0','1','1','0','b']
TM_header = 1

try:
  for line in tm_rules_file:
    match1 = re.match ('^(\S+):(0|1|b):(0|1|b):(L|R):(\S+)\s*\;*.*$', line)
    match2 = re.match ('^(\S+)\s*\;*.*$', line)
    if match1:
      #print match.group(1), match.group(2), match.group(3), match.group(4), match.group(5)
      tm_state = match1.group(1)
      tm_symbol1 = match1.group(2)
      tm_symbol2 = match1.group(3)
      tm_header_direction = match1.group(4)
      tm_next_state = match1.group(5)
      TM_rules.append(TM_rule(tm_state,tm_symbol1,tm_symbol2,tm_header_direction,tm_next_state))
    elif match2:
      tm_state = match2.group(1)
      TM_rules.append(TM_rule(tm_state,"","","",""))
      break

finally:
  tm_rules_file.close()

#for rule in TM_rules:
#  rule.__print__()

print "INPUT: ",
for a in TM_input:
  print a,
print "\n"
print "START."

TM_state = TM_rules[0].TM_first_state

while TM_state:
  for rule in TM_rules:
    if rule.TM_first_state == TM_state and rule.TM_symbol1 == TM_input[TM_header]:
      print "%s -> %s|%s%s -> %s" % (rule.TM_first_state, rule.TM_symbol1, rule.TM_symbol2, rule.TM_header_direction, rule.TM_next_state)
      TM_input[TM_header] = rule.TM_symbol2
      if rule.TM_header_direction == "L":
        TM_header = TM_header + 1
      else:
        TM_header = TM_header - 1
      if TM_header == len(TM_input):
        TM_input.append("b")
      elif TM_header == 0:
        TM_header = 1
      TM_state = rule.TM_next_state
      break 
    elif rule.TM_first_state == TM_state and rule.TM_next_state == "":
      print "HALT.\n"
      TM_state = ""
      break

print "OUTPUT: ",
for a in TM_input:
  print a,

